package com.example.securityproject.demos.service;

import com.example.securityproject.demos.entity.TUser;
import com.example.securityproject.demos.entity.User;
import com.example.securityproject.demos.vo.MenuVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/*
 * @description:
 * @author: Jiangjb
 * @date: 2024/4/7 15:27
 **/
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private TUserService tUserService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser loginUser = tUserService.loadUserByUsername(username);
        //查询不到该用户信息抛异常
        if(loginUser == null) {
            throw new RuntimeException("用户名或者密码错误");
        }
        loginUser.setPassword(passwordEncoder.encode(loginUser.getPassword()));
        User user = new User(loginUser);
        return user;
    }

//    @Override
//    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
//        /**
//         * 1/通过userName 获取到userInfo信息
//         * 2/通过User（UserDetails）返回details。
//         */
//        //通过userName获取用户信息
//        TUser userInfo = tUserService.getUserInfoByUsername(userName);
//        if (userInfo == null) {
//            throw new UsernameNotFoundException("not found");
//        }
////        //定义权限列表
//        List<MenuVO> menus = tUserService.queryMenus(userName);
//        List<GrantedAuthority> authorities = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(menus)) {
//            for (MenuVO vo : menus) {
//                // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
//                authorities.add(new SimpleGrantedAuthority("ROLE_" + vo.getRoleName()));
//            }
//        }
//        User userDetails = new User(userInfo.getUsername(), passwordEncoder.encode(userInfo.getPassword()), authorities);
//        return userDetails;
//    }
}
